package sample3.provider.ddl;

import android.text.TextUtils;

@SuppressWarnings("all")
public class SqliteViewBuilder extends AbsDdlBuilder {
	private String mFrom;
	private String mWhere;
	private String mGroupBy;
	private String mHaving;
	private String mOrderBy;

	public SqliteViewBuilder(String name) {
		super(name);
	}

	public SqliteViewBuilder addSelectPart(String columnAlias, String selectPart) {
		addColumn(selectPart + " AS " + columnAlias);
		return this;
	}

	public SqliteViewBuilder addSelect(String columnAlias, String selectPartFormat, String... text) {
		return addSelectPart(columnAlias, String.format(selectPartFormat, text));
	}

	public SqliteViewBuilder setFrom(String from) {
		this.mFrom = from;
		return this;
	}

	public SqliteViewBuilder setFrom(String fromPartFormat, String... text) {
		return setFrom(String.format(fromPartFormat, text));
	}

	public SqliteViewBuilder setWhere(String where) {
		this.mWhere = where;
		return this;
	}

	public SqliteViewBuilder setWhere(String wherePartFormat, String... text) {
		return setWhere(String.format(wherePartFormat, text));
	}

	public SqliteViewBuilder setGroupBy(String groupBy) {
		this.mGroupBy = groupBy;
		return this;
	}

	public SqliteViewBuilder setGroupBy(String groupByPartFormat, String... text) {
		return setGroupBy(String.format(groupByPartFormat, text));
	}

	public SqliteViewBuilder setOrderBy(String orderBy) {
		this.mOrderBy = orderBy;
		return this;
	}

	public SqliteViewBuilder setOrderBy(String orderByPartFormat, String... text) {
		return setOrderBy(String.format(orderByPartFormat, text));
	}

	public SqliteViewBuilder setHaving(String having) {
		this.mHaving = having;
		return this;
	}

	public SqliteViewBuilder setHaving(String havingByPartFormat, String... text) {
		return setHaving(String.format(havingByPartFormat, text));
	}

	@Override
	String toDropSql() {
		return "DROP VIEW IF EXISTS " + getName();
	}

	@Override
	String toCreateSql() {
		StringBuilder sql = new StringBuilder();
		// start
		sql.append("CREATE VIEW INDEX IF NOT EXISTS ").append(getName()).append(" AS").append('\n');
		// select
		sql.append("SELECT ");
		boolean addComma = false;
		for (String part : getColumn()) {
			if (addComma) {
				sql.append('\n').append("      ,");
			}
			addComma = true;
			sql.append(part);
		}
		// from
		if (!TextUtils.isEmpty(mFrom)) {
			sql.append('\n').append("  FROM ").append(mFrom);
		}

		if (!TextUtils.isEmpty(mWhere)) {
			sql.append('\n').append(" WHERE ").append(mWhere);
		}

		if (!TextUtils.isEmpty(mGroupBy)) {
			sql.append('\n').append(" GROUP BY ").append(mGroupBy);
		}

		if (!TextUtils.isEmpty(mHaving)) {
			sql.append('\n').append("HAVING ").append(mHaving);
		}

		if (!TextUtils.isEmpty(mOrderBy)) {
			sql.append('\n').append(" ORDER BY ").append(mOrderBy);
		}
		return sql.toString();
	}
}
